package org.example;

public class leetcode {
    public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length();
        int n = text2.length();
        char[] s = text1.toCharArray();
        char[] t = text2.toCharArray();
        //text1[i] == text2[j] dp[i][j] = dp[i-1][j-1]+1;
        //text1[i] != text2[j] dp[i][j] = max(dp[i-1][j], dp[i][j-1])
        int[][] dp = new int[m][n];
        if(s[0] == t[0]){
            dp[0][0] = 1;
        }
        for(int i = 1 ;i < n; i++){
            if(dp[0][i-1] == 1 || s[0] == t[i]){
                dp[0][i] = 1;
            }
        }
        for(int i = 1; i < m; i++){
            if(dp[i-1][0] == 1 || s[i] == t[0]){
                dp[i][0] = 1;
            }
        }
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                if(s[i] == t[j]){
                    dp[i][j] = dp[i-1][j-1]+1;
                }else{
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }
        // for(int i = 0; i < m; i++){
        //     for(int j = 0; j < n; j++){
        //         System.out.print(dp[i][j] + " ");
        //     }
        //     System.out.println();
        // }
        return dp[m-1][n-1];
    }
}
